package jgl.vajra.operator.part.home.activity;

import android.content.Intent;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;

import com.alibaba.fastjson.JSONObject;
import com.gyf.immersionbar.ImmersionBar;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import jgl.vajra.operator.R;
import jgl.vajra.operator.databinding.ActivityHomeBinding;
import jgl.vajra.operator.event.PushMachineOrderEvent;
import jgl.vajra.operator.manager.AccountManager;
import jgl.vajra.operator.manager.BaiduPositioningManager;
import jgl.vajra.operator.manager.FragmentManager;
import jgl.vajra.operator.manager.IntentManager;
import jgl.vajra.operator.manager.UMShareManager;
import jgl.vajra.operator.netty.MessageOrderBean;
import jgl.vajra.operator.part.home.contract.HomeContract;
import jgl.vajra.operator.part.home.fragment.GrabOrderFragment;
import jgl.vajra.operator.part.home.fragment.MinePageFragment;
import jgl.vajra.operator.part.home.fragment.OrderPageFragment;
import jgl.vajra.operator.part.home.fragment.TaskPageFragment;
import jgl.vajra.operator.part.home.viewModel.HomeViewModel;
import jgl.vajra.operator.widget.base.BaseFragmentAdapter;
import jgl.vajra.operator.widget.mvvm.factory.CreateViewModel;
import jgl.vajra.operator.widget.mvvm.view.BaseMVVMActivity;
import jgl.vajra.operator.widget.permissions.PermissionListener;
import jgl.vajra.operator.widget.permissions.PermissionsUtil;
import jgl.vajra.operator.widget.utils.ToastUtils;

/**
 * Created by Administrator on 2019/4/25.
 */
@CreateViewModel(HomeViewModel.class)
public class HomeActivity extends BaseMVVMActivity<HomeViewModel, ActivityHomeBinding> implements HomeContract.View {

    private List<Fragment> mFragmentList = new ArrayList<>();
    private long exitTime;

    private int activityShowCounts;

    @Override
    public int getLayoutId() {
        return R.layout.activity_home;
    }

    @Override
    public void initView() {
        super.initView();
        ImmersionBar.with(HomeActivity.this).statusBarColor(R.color.white).navigationBarColor(R.color.white).fitsSystemWindows(true).statusBarDarkFont(true, 0.2f).init();

        AccountManager.getInstance().getVersionUpdate(this);
        GrabOrderFragment grabOrderFragment = FragmentManager.getGrabOrderFragment();
        // HomePageFragment homePageFragment = FragmentManager.getHomePageFragment();
        TaskPageFragment taskPageFragment = FragmentManager.getTaskPageFragment();
        OrderPageFragment orderPageFragment = FragmentManager.getOrderPageFragment();
        MinePageFragment minePageFragment = FragmentManager.getMinePageFragment();

        mFragmentList.add(grabOrderFragment);
        // mFragmentList.add(homePageFragment);
        mFragmentList.add(taskPageFragment);
        mFragmentList.add(orderPageFragment);
        mFragmentList.add(minePageFragment);

        BaseFragmentAdapter adapter = new BaseFragmentAdapter(getSupportFragmentManager(), mFragmentList, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        mBinding.viewPager.setAdapter(adapter);
        mBinding.viewPager.setOffscreenPageLimit(mFragmentList.size());
        mBinding.bbl.setViewPager(mBinding.viewPager);
        PermissionsUtil.requestPermission(this, new PermissionListener() {
                    @Override
                    public void permissionGranted(@NonNull String[] permissions) {
                    }

                    @Override
                    public void permissionDenied(@NonNull String[] permissions) {
                        //  ToastUtils.showShort("请到设置-权限管理中开启");
                    }
                }, permissions, false, null
        );
//        LocationLocalManager.getInstance().initLocation(this);
        BaiduPositioningManager.getInstance().initLocation(this);
        if (getIntent() != null && Intent.ACTION_VIEW.equals(getIntent().getAction())) {
            IntentManager.toDeepLinkActivity(this, getIntent().getData(), false);
        }
//        JPushManager.getInstance().addCourseTagIdToJPushTag();

        /**
         * 这个app监听所有activity的状态变化回调；
         */
       /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
                @Override
                public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {

                }

                @Override
                public void onActivityStarted(@NonNull Activity activity) {
                    activityShowCounts++;
                    if(activityShowCounts==1){

                        //说明进入了前台；
                        Logger.d("进入了前台"+ ClientHandler.isLogin);
                        *//*if (!ClientHandler.isLogin) {
                            Logger.d("进入了 进来连接了啊");
                            ImConnection.getInstance().close();//断开连接
                            ImConnection.getInstance().connect();//连接
                        }*//*
                        //ImConnection.getInstance().close();//断开连接
                        ImConnection.getInstance().connect();//连接
                    }
                }

                @Override
                public void onActivityResumed(@NonNull Activity activity) {

                }

                @Override
                public void onActivityPaused(@NonNull Activity activity) {

                }

                @Override
                public void onActivityStopped(@NonNull Activity activity) {
                    activityShowCounts--;
                    if(activityShowCounts==0){
                        //说明进入了后台；
                        Logger.d("进入了后台");
                    }
                }

                @Override
                public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

                }

                @Override
                public void onActivityDestroyed(@NonNull Activity activity) {

                }
            });
        }*/

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareManager.getInstance().onActivityResult(this, requestCode, resultCode, data);
    }

    @Override
    public void onBackPressed() {
        if (mBinding != null && mBinding.bbl.getCurrentItem() == 0) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                ToastUtils.showShort(R.string.Click_again_to_return_desktop);
                exitTime = System.currentTimeMillis();
            } else {
                // System.exit(0)
                moveTaskToBack(true);
                Intent launcherIntent = new Intent(Intent.ACTION_MAIN);
                launcherIntent.addCategory(Intent.CATEGORY_HOME);
                startActivity(launcherIntent);

            }
        } else if (mBinding != null && mBinding.bbl.getCurrentItem() != 0) {
            mBinding.bbl.setCurrentItem(0);
        } else {
            moveTaskToBack(true);
            super.onBackPressed();
        }
    }

    @Override
    public void initEvent() {
        super.initEvent();
        mBinding.bbl.setBottomMenuOnPageChangeListener((bottomMenuItem, previousPosition, currentPosition) -> {
            switch (currentPosition) {
               /* case 1:
                    ImmersionBar.with(HomeActivity.this).statusBarColor(R.color.color_012BB2).navigationBarColor(R.color.white).fitsSystemWindows(true).statusBarDarkFont(false, 0.2f).init();
                    break;*/
                case 0:
                case 1:
                case 2:
                case 3:
                    ImmersionBar.with(HomeActivity.this).statusBarColor(R.color.white).navigationBarColor(R.color.white).fitsSystemWindows(true).statusBarDarkFont(true, 0.2f).init();
                    break;

            }
        });
    }

    @Override
    protected boolean isNeedLoadStatusBar() {
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    protected boolean isRegisterEvent() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPushMachineOrderEvent(PushMachineOrderEvent event) {
        String content = event.content;
        MessageOrderBean beanMessage = JSONObject.parseObject(content, MessageOrderBean.class);

        Logger.d(beanMessage.orderId + "订单号");
        mBinding.viewPager.setCurrentItem(2);
    }
}
